package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.date.DateUtil;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.basic.exception.BizException;
import top.tangyh.basic.utils.DateUtils;
import top.tangyh.lamp.care.entity.*;
import top.tangyh.lamp.care.manager.LeavePatientsManager;
import top.tangyh.lamp.care.service.*;
import top.tangyh.lamp.care.vo.result.HuxiJiHaveRVO;
import top.tangyh.lamp.care.vo.result.TemperateIODataVO;
import top.tangyh.lamp.care.vo.result.TemperatureDataVO;
import top.tangyh.lamp.common.constant.ModelItemConstant;
import top.tangyh.lamp.common.properties.SystemProperties;
import top.tangyh.lamp.common.utils.PDateUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author: zqb
 * @date: 2024/7/24 15:51
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TemperatureServiceImpl implements TemperatureService {

    @Autowired
    protected SystemProperties systemProperties;

    private final BPatEventService bPatEventService;

    private final TemperatureDetailService temperatureDetailService;

    private final BPgRecordService bPgRecordService;

    private final BIoRecordService bIoRecordService;

    @Override
    public TemperatureDataVO getTemperatureDatas(String patientIdent, String hospitalNumber,   Long rkTime, Long ckTime) {
        if (null == rkTime ) {
            throw new BizException("病人入科时间不能为空");
        }


        // 初始化总数据清单
        TemperatureDataVO temperatureList = new TemperatureDataVO();

        LocalDateTime rkLocalTime=PDateUtils.getDateTimeOfTimestamp(rkTime);

        //入科时间
        String rkTimeStr = rkLocalTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

//        Long rkTimeLong = PDateUtils.getTimestampOfDateTime(yxHl7EventPORk.getEventTime());
        List<String> dates = new ArrayList<>();
        dates.add(rkTimeStr);

        //出院时间
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String cYTimeStr = "";
//        if (null == yxHl7EventPOCY) {
//            //当前时间 如果出院时间为空 结束时间就以当前时间为准
//            LocalDateTime time = LocalDateTime.now();
//            String nowStr = dtf2.format(time);
//            cYTimeStr = nowStr;
//        } else {
//            cYTimeStr = yxHl7EventPOCY.getEventTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        }

        String ckTimeStr="";
        if(null==ckTime){
            //当前系统时间
            LocalDateTime ckTimeLocalTime=LocalDateTime.now();
            ckTimeStr=ckTimeLocalTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            ckTime= PDateUtils.getTimestampOfDateTime(ckTimeLocalTime);
        }else{
            LocalDateTime ckTimeLocalTime=PDateUtils.getDateTimeOfTimestamp(ckTime);
            ckTimeStr=ckTimeLocalTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }

//        if (null != rkTime) {
//            rkTimeStr = PDateUtils.dateToStr(new Date(rkTime));
//        }
//        if (null != ckTime) {
//            cYTimeStr = PDateUtils.dateToStr(new Date(ckTime));
//        }



        //【事件】 -------------------------------------------------------------------------------------------------------------》
        String icuCode = systemProperties.getIcuCode();
        List<BPatEvent> listEvent = bPatEventService.selectEventListByParam(hospitalNumber, rkTimeStr, ckTimeStr, icuCode);
        temperatureList.setListEvent(listEvent);


        //
        //ecg,pr,resp,ibpD,ibpS,nIbpD,nIbpS; 查询 ck表 读取设备 数据 这个暂时不做具体实现等解析那边落位再根据实际情况开发
        Map<String, List<BObsvRecord>> allrecord = temperatureDetailService.getDevTwdObsvRecord(patientIdent, hospitalNumber, rkTimeStr, ckTimeStr);

        //【体温】-------------------------------------------------------------------------------------------------------------》
        /* 体温单-体温 gcx_t_s.
        肛温	gcx_clgj_gw
        腋温	gcx_clgj_yw
        口温	gcx_clgj_kw
        耳温	gcx_clgj_ew
        四个温度的值 标识 gcx_T
        物理/药物降温	float	gcx_wlywjw
        */
        Map<String, List<BObsvRecord>> collectsTw = temperatureDetailService.getCollectsTw(hospitalNumber, rkTime, ckTime);
        temperatureList.setCollectsTw(collectsTw);

        //【脉搏、心率】 -------------------------------------------------------------------------------------------------------------》
        /* 脉搏	integer	pr
        心率	integer	ecg */
        List<BObsvRecord> dataBObsvRecord_PE=new ArrayList<>();
        List<BObsvRecord> dataBObsvRecord_RESP=new ArrayList<>();
        List<BObsvRecord> dataBObsvRecord_XY=new ArrayList<>();
        if(null!=allrecord){
            dataBObsvRecord_PE= allrecord.get("pe");
            dataBObsvRecord_RESP= allrecord.get("resp");
            dataBObsvRecord_XY= allrecord.get("xy");
        }

//        Map<String, List<BObsvRecord>> collectsPulseHeartRateResult = temperatureDetailService.getCollectsPulseHeartRate(hospitalNumber, rkTimeStr, cYTimeStr, dataBObsvRecord_PE);
        //【脉搏、心率】 -------------------------------------------------------------------------------------------------------------》
        /* 脉搏	integer	pr
        心率	integer	ecg */
        Map<String, List<BObsvRecord>> collectsPulseHeartRateResult = temperatureDetailService.getCollectsPulseHeartRate(hospitalNumber, rkTimeStr, ckTimeStr);

        temperatureList.setCollectsPulseHeartRate(collectsPulseHeartRateResult);

        //【疼痛】 -------------------------------------------------------------------------------------------------------------》
        // 按照时段分组 把所有数据给前端 通过hours 属性匹配纵向坐标小时段值
        List<BPgRecord> listTt = bPgRecordService.getPgRecodOfTengTong(hospitalNumber, rkTimeStr, ckTimeStr, ModelItemConstant.PGPF_TT);
        temperatureList.setListTt(listTt);


        //手动判断呼吸机 关停 非正常流程 新系统不一定需要这个功能
        //        List<HuxiJiHaveRVO> huxiJiHaveRVOList = yxRespiratorStatusService.getHandRList(hospitalNumber, yxHl7EventPORk.getEventTime());
//        temperatureList.setListHuxiJiHaveR(huxiJiHaveRVOList);


        //【呼吸】
        // -获取观察项信息（生命体征） 是否来源于设备通过新增标识字段区分
        //呼吸值取整点（02:00,06:00,10:00,14:00,18:00,22:00）,若无整点数值，则取离整点最近的呼吸值
        // Map<String, List<BObsvRecord>> collectsHuxiResult = temperatureDetailService.getCollectsHuxi(hospitalNumber, rkTimeStr, cYTimeStr, dataBObsvRecord_RESP);
        Map<String, List<BObsvRecord>> collectsHuxiResult = temperatureDetailService.getCollectsHuxi(hospitalNumber, rkTimeStr, ckTimeStr);
        temperatureList.setCollectsHuxi(collectsHuxiResult);


        //【血压】 -------------------------------------------------------------------------------------------------------------》
        // 产品需求要求 只取有创血压下面的 收缩压和舒张压
//        有创血压	gcx_ycxy_s
//        有创舒张压	integer	ibpD
//        有创收缩压	integer	ibpS
        // 无创血压	gcx_wcxy_s
//        无创舒张压	integer	nIbpD
//        无创收缩压	integer	nIbpS
        // Map<String, List<BObsvRecord>> collectsBloodPressureResult = temperatureDetailService.getCollectsBloodPressure(hospitalNumber, rkTimeStr, cYTimeStr, dataBObsvRecord_XY);
        Map<String, List<BObsvRecord>> collectsBloodPressureResult = temperatureDetailService.getCollectsBloodPressure(hospitalNumber, rkTimeStr, ckTimeStr);
        temperatureList.setCollectsBloodPressure(collectsBloodPressureResult);

        //【大便】-------------------------------------------------------------------------------------------------------------》
        /*
        是否失禁	gcx_sfsj
        造口/人工肛门	gcx_zkrggm
        大便次数	string	gcx_dbcs */
        List<Map> listCollectsShit = temperatureDetailService.getCollectsShit(hospitalNumber, rkTimeStr, ckTimeStr);
        temperatureList.setCollectsShit(listCollectsShit);

        //尿量 -------------------------------------------------------------------------------------------------------------》
        //需求： 尿量（24小时内，7：00-7：00）：数据获取出量中的尿量700，如管道管理中该患者有使用低危管道中的“导尿管”，即展示“数值/C”,例：“700/C”
        List<TemperateIODataVO> nlResult = temperatureDetailService.getListOutNl(hospitalNumber, rkTimeStr, ckTimeStr);
        temperatureList.setListOutNl(nlResult);

        //【体重】  -------------------------------------------------------------------------------------------------------------》
        //不需要后端做 前端可以直接做

        //【引流量】 -------------------------------------------------------------------------------------------------------------》
        List<TemperateIODataVO> listYll = bIoRecordService.selectSumOfLiuLiangList(hospitalNumber, rkTimeStr, ckTimeStr);
        temperatureList.setListOutYll(listYll);
        //【出入量】 总量统计 每天总和统计
        List<TemperateIODataVO> listOutIn = bIoRecordService.selectSumOfOutInList(hospitalNumber, rkTimeStr, ckTimeStr);
        temperatureList.setListOutIn(listOutIn);

        return temperatureList;
    }
//    @Override
//    public TemperatureDataVO getTemperatureDatas(String patientIdent, String hospitalNumber, BHl7Event yxHl7EventPORk, BHl7Event yxHl7EventPOCY, Long rkTime, Long ckTime) {
//        if (null == yxHl7EventPORk ) {
//            throw new BizException("病人入科时间不能为空");
//        }
//
//        if (null == rkTime) {
//            throw new BizException("病人入科时间不能为空");
//        }
//        if (null == yxHl7EventPORk.getEventTime()) {
//            throw new BizException("病人入科时间不能为空");
//        }
//        // 初始化总数据清单
//        TemperatureDataVO temperatureList = new TemperatureDataVO();
//
//
//        //入科时间
//        String rkTimeStr = yxHl7EventPORk.getEventTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//        Long rkTimeLong = PDateUtils.getTimestampOfDateTime(yxHl7EventPORk.getEventTime());
//        List<String> dates = new ArrayList<>();
//        dates.add(rkTimeStr);
//
//        //出院时间
//        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//        String cYTimeStr = "";
//        if (null == yxHl7EventPOCY) {
//            //当前时间 如果出院时间为空 结束时间就以当前时间为准
//            LocalDateTime time = LocalDateTime.now();
//            String nowStr = dtf2.format(time);
//            cYTimeStr = nowStr;
//        } else {
//            cYTimeStr = yxHl7EventPOCY.getEventTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//        }
//
//        if (null != rkTime) {
//            rkTimeStr = PDateUtils.dateToStr(new Date(rkTime));
//        }
//        if (null != ckTime) {
//            cYTimeStr = PDateUtils.dateToStr(new Date(ckTime));
//        }
//
//        Long cYTimeLong = DateUtil.parseDateTime(cYTimeStr).getTime();
//
//        //【事件】 -------------------------------------------------------------------------------------------------------------》
//        String icuCode = systemProperties.getIcuCode();
//        List<BPatEvent> listEvent = bPatEventService.selectEventListByParam(hospitalNumber, rkTimeStr, cYTimeStr, icuCode);
//        temperatureList.setListEvent(listEvent);
//
//
//        //
//        //ecg,pr,resp,ibpD,ibpS,nIbpD,nIbpS; 查询 ck表 读取设备 数据 这个暂时不做具体实现等解析那边落位再根据实际情况开发
//        Map<String, List<BObsvRecord>> allrecord = temperatureDetailService.getDevTwdObsvRecord(patientIdent, hospitalNumber, rkTimeStr, cYTimeStr);
//
//        //【体温】-------------------------------------------------------------------------------------------------------------》
//        /* 体温单-体温 gcx_t_s.
//        肛温	gcx_clgj_gw
//        腋温	gcx_clgj_yw
//        口温	gcx_clgj_kw
//        耳温	gcx_clgj_ew
//        四个温度的值 标识 gcx_T
//        物理/药物降温	float	gcx_wlywjw
//        */
//        Map<String, List<BObsvRecord>> collectsTw = temperatureDetailService.getCollectsTw(hospitalNumber, rkTimeLong, cYTimeLong);
//        temperatureList.setCollectsTw(collectsTw);
//
//        //【脉搏、心率】 -------------------------------------------------------------------------------------------------------------》
//        /* 脉搏	integer	pr
//        心率	integer	ecg */
//        List<BObsvRecord> dataBObsvRecord_PE=new ArrayList<>();
//        List<BObsvRecord> dataBObsvRecord_RESP=new ArrayList<>();
//        List<BObsvRecord> dataBObsvRecord_XY=new ArrayList<>();
//        if(null!=allrecord){
//            dataBObsvRecord_PE= allrecord.get("pe");
//            dataBObsvRecord_RESP= allrecord.get("resp");
//            dataBObsvRecord_XY= allrecord.get("xy");
//        }
//
////        Map<String, List<BObsvRecord>> collectsPulseHeartRateResult = temperatureDetailService.getCollectsPulseHeartRate(hospitalNumber, rkTimeStr, cYTimeStr, dataBObsvRecord_PE);
//        //【脉搏、心率】 -------------------------------------------------------------------------------------------------------------》
//        /* 脉搏	integer	pr
//        心率	integer	ecg */
//        Map<String, List<BObsvRecord>> collectsPulseHeartRateResult = temperatureDetailService.getCollectsPulseHeartRate(hospitalNumber, rkTimeStr, cYTimeStr);
//
//        temperatureList.setCollectsPulseHeartRate(collectsPulseHeartRateResult);
//
//        //【疼痛】 -------------------------------------------------------------------------------------------------------------》
//        // 按照时段分组 把所有数据给前端 通过hours 属性匹配纵向坐标小时段值
//        List<BPgRecord> listTt = bPgRecordService.getPgRecodOfTengTong(hospitalNumber, rkTimeStr, cYTimeStr, ModelItemConstant.PGPF_TT);
//        temperatureList.setListTt(listTt);
//
//
//        //手动判断呼吸机 关停 非正常流程 新系统不一定需要这个功能
//        //        List<HuxiJiHaveRVO> huxiJiHaveRVOList = yxRespiratorStatusService.getHandRList(hospitalNumber, yxHl7EventPORk.getEventTime());
////        temperatureList.setListHuxiJiHaveR(huxiJiHaveRVOList);
//
//
//        //【呼吸】
//        // -获取观察项信息（生命体征） 是否来源于设备通过新增标识字段区分
//        //呼吸值取整点（02:00,06:00,10:00,14:00,18:00,22:00）,若无整点数值，则取离整点最近的呼吸值
//       // Map<String, List<BObsvRecord>> collectsHuxiResult = temperatureDetailService.getCollectsHuxi(hospitalNumber, rkTimeStr, cYTimeStr, dataBObsvRecord_RESP);
//        Map<String, List<BObsvRecord>> collectsHuxiResult = temperatureDetailService.getCollectsHuxi(hospitalNumber, rkTimeStr, cYTimeStr);
//        temperatureList.setCollectsHuxi(collectsHuxiResult);
//
//
//        //【血压】 -------------------------------------------------------------------------------------------------------------》
//        // 产品需求要求 只取有创血压下面的 收缩压和舒张压
////        有创血压	gcx_ycxy_s
////        有创舒张压	integer	ibpD
////        有创收缩压	integer	ibpS
//        // 无创血压	gcx_wcxy_s
////        无创舒张压	integer	nIbpD
////        无创收缩压	integer	nIbpS
//       // Map<String, List<BObsvRecord>> collectsBloodPressureResult = temperatureDetailService.getCollectsBloodPressure(hospitalNumber, rkTimeStr, cYTimeStr, dataBObsvRecord_XY);
//        Map<String, List<BObsvRecord>> collectsBloodPressureResult = temperatureDetailService.getCollectsBloodPressure(hospitalNumber, rkTimeStr, cYTimeStr);
//        temperatureList.setCollectsBloodPressure(collectsBloodPressureResult);
//
//        //【大便】-------------------------------------------------------------------------------------------------------------》
//        /*
//        是否失禁	gcx_sfsj
//        造口/人工肛门	gcx_zkrggm
//        大便次数	string	gcx_dbcs */
//        List<Map> listCollectsShit = temperatureDetailService.getCollectsShit(hospitalNumber, rkTimeStr, cYTimeStr);
//        temperatureList.setCollectsShit(listCollectsShit);
//
//        //尿量 -------------------------------------------------------------------------------------------------------------》
//        //需求： 尿量（24小时内，7：00-7：00）：数据获取出量中的尿量700，如管道管理中该患者有使用低危管道中的“导尿管”，即展示“数值/C”,例：“700/C”
//        List<TemperateIODataVO> nlResult = temperatureDetailService.getListOutNl(hospitalNumber, rkTimeStr, cYTimeStr);
//        temperatureList.setListOutNl(nlResult);
//
//        //【体重】  -------------------------------------------------------------------------------------------------------------》
//        //不需要后端做 前端可以直接做
//
//        //【引流量】 -------------------------------------------------------------------------------------------------------------》
//        List<TemperateIODataVO> listYll = bIoRecordService.selectSumOfLiuLiangList(hospitalNumber, rkTimeStr, cYTimeStr);
//        temperatureList.setListOutYll(listYll);
//        //【出入量】 总量统计 每天总和统计
//        List<TemperateIODataVO> listOutIn = bIoRecordService.selectSumOfOutInList(hospitalNumber, rkTimeStr, cYTimeStr);
//        temperatureList.setListOutIn(listOutIn);
//
//        return temperatureList;
//    }
}
